package com.kunkun.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.kunkun.subject.common.entity.PageResult;
import com.kunkun.subject.common.enums.IsDeletedFlagEnum;
import com.kunkun.subject.domain.convert.SubjectCategoryConverter;
import com.kunkun.subject.domain.convert.SubjectInfoConverter;
import com.kunkun.subject.domain.entity.SubjectCategoryBO;
import com.kunkun.subject.domain.entity.SubjectInfoBO;
import com.kunkun.subject.domain.entity.SubjectLabelBO;
import com.kunkun.subject.domain.service.SubjectCategoryDomainService;
import com.kunkun.subject.domain.util.CacheUtil;
import com.kunkun.subject.infra.basic.entity.SubjectCategory;
import com.kunkun.subject.infra.basic.entity.SubjectInfo;
import com.kunkun.subject.infra.basic.entity.SubjectLabel;
import com.kunkun.subject.infra.basic.entity.SubjectMapping;
import com.kunkun.subject.infra.basic.service.SubjectCategoryService;
import com.kunkun.subject.infra.basic.service.SubjectLabelService;
import com.kunkun.subject.infra.basic.service.SubjectMappingService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {
    @Resource
    private SubjectCategoryService subjectCategoryService;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private ThreadPoolExecutor labelThreadPool;

    @Resource
    private CacheUtil cacheUtil;

    @Override
    public void add(SubjectCategoryBO subjectCategoryBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.add.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectCategoryService.insert(subjectCategory);

    }

    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> boList = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryList);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryPrimaryCategory.boList:{}",
                    JSON.toJSONString(boList));
        }

        boList.forEach(bo->{
            Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
            bo.setCount(subjectCount);
        });

        return boList;

    }

    @Override
    public Boolean update(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    @Override
    public Boolean delete(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    @Override
    public PageResult<SubjectCategoryBO> getCategoryList(SubjectCategoryBO subjectCategoryBO) {
        PageResult<SubjectCategoryBO> pageResult = new PageResult<>();
        //设置页码和每页大小
        pageResult.setPageNo(subjectCategoryBO.getPageNo());
        pageResult.setPageSize(subjectCategoryBO.getPageSize());
        int start = (subjectCategoryBO.getPageNo() - 1) * subjectCategoryBO.getPageSize();
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        int count = subjectCategoryService.countByCondition(subjectCategory);
        if (count == 0) {
            return pageResult;
        }



        return null;
    }

    @SneakyThrows
    @Override
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        //查询当前大类下所有分类
        Integer id = subjectCategoryBO.getId();
        String cacheKey = "categoryAndLabel." + subjectCategoryBO.getId();
        List subjectCategoryBOS = cacheUtil.getResult(cacheKey,
                SubjectCategoryBO.class, (key) -> getSubjectCategoryBOS(id));
//        String content = localCache.getIfPresent(cacheKey);
//        List<SubjectCategoryBO> subjectCategoryBOS = new LinkedList<>();
//        if (StringUtils.isBlank(content)) {
//            subjectCategoryBOS = getSubjectCategoryBOS(subjectCategoryBO.getId());
//            localCache.put(cacheKey,JSON.toJSONString(subjectCategoryBOS));
//        }else {
//            subjectCategoryBOS = JSON.parseArray(content, SubjectCategoryBO.class);
//
//        }
        return subjectCategoryBOS;
    }



    private List<SubjectCategoryBO> getSubjectCategoryBOS(Integer categoryId) {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryDomainServiceImpl.queryCategoryAndLabel.bo:{}",
                    JSON.toJSONString(subjectCategoryList));
        }
        List<SubjectCategoryBO> subjectCategoryBOS = SubjectCategoryConverter
                .INSTANCE.convertBoToCategory(subjectCategoryList);
        // 创建结果容器（注意线程安全问题）
        Map<Integer,List<SubjectLabelBO>> map = new HashMap<>();
        //CompletableFuture.supplyAsync是异步处理数据的好方法，特别是当处理过程可能涉及I/O操作或长时间计算时。
        //这里通过labelThreadPool指定了一个线程池来执行这些异步任务
        // 构建并行任务流
        List<CompletableFuture<Map<Integer,List<SubjectLabelBO>>>> completableFutureList = subjectCategoryBOS
                .stream().map(categoty ->  // 每个分类创建独立异步任务
                    CompletableFuture.supplyAsync(() -> getLabelBOList(categoty), // 实际数据加载方法
                            labelThreadPool)// 指定专用线程池
                ).collect(Collectors.toList());
        // 任务结果处理
        completableFutureList.forEach(future -> {
            try {
                Map<Integer,List<SubjectLabelBO>> resultMap = future.get();
                map.putAll(resultMap);
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        });


        //一次性获取标签信息
//        List<FutureTask<Map<Integer,List<SubjectLabelBO>>>> futuresTaskList = new LinkedList<>();
//        //线程池并发调用
//        Map<Integer,List<SubjectLabelBO>> map = new HashMap<>();
//        subjectCategoryBOS.forEach(category ->{
//
//            FutureTask<Map<Integer,List<SubjectLabelBO>>> futuresTask = new FutureTask<>(()->
//                    getLabelBOList(category));
//            futuresTaskList.add(futuresTask);
//            labelThreadPool.submit(futuresTask);
//        });
//        for (FutureTask<Map<Integer,List<SubjectLabelBO>>> futureTask : futuresTaskList) {
//            Map<Integer,List<SubjectLabelBO>> resultMap = futureTask.get();
//            if (CollectionUtils.isEmpty(resultMap)) {
//                continue;
//            }
//            map.putAll(resultMap);
//        }
        subjectCategoryBOS.forEach(categoryBO ->{
            categoryBO.setSubjectLabelBOList(map.get(categoryBO.getId()));
        });

        return subjectCategoryBOS;
    }

    private Map<Integer,List<SubjectLabelBO>> getLabelBOList(SubjectCategoryBO category) {
        if (log.isInfoEnabled()) {
            log.info("getLabelBOList.bo:{}", JSON.toJSONString(category));
        }
        Map<Integer,List<SubjectLabelBO>> labelMap = new HashMap<>();

        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(category.getId());
        List<SubjectMapping> subjectMappings = subjectMappingService.queryLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(subjectMappings)) {
            return null;
        }
        //从 subjectMappings 集合中提取每个 SubjectMapping 对象的 labelId（通过调用 getLabelId 方法），
        // 并将这些 labelId 收集到一个新的 List 中
        List<Integer> labelIdList = subjectMappings.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> subjectLabels = subjectLabelService.batchQueryById(labelIdList);
        List<SubjectLabelBO> labelBOList = new LinkedList<>();
        subjectLabels.forEach(label->{
            SubjectLabelBO labelBO = new SubjectLabelBO();
            labelBO.setId(label.getId());
            labelBO.setLabelName(label.getLabelName());
            labelBO.setCategoryId(label.getCategoryId());
            labelBO.setSortNum(label.getSortNum());
            labelBOList.add(labelBO);
        });
        labelMap.put(category.getId(), labelBOList);
        return labelMap;
    }


}
